'''游戏工具类'''
import sys,pygame
from bullet import Bullet
from alien import Alien
from pygame.sprite import groupcollide,spritecollideany
from time import sleep

def check_event(setObj,ship,screen,bullets,stats,btn):
    '''监听各种事件的触发'''
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouseX,mmouseY = pygame.mouse.get_pos() #获取当前鼠标位置
            check_btn_click(stats,btn,mouseX,mmouseY)
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q: #Q键退出游戏
                sys.exit()
            move_handler(ship,event.key,True)
            shoot(setObj,ship,event.key,screen,bullets)

        elif event.type == pygame.KEYUP:
            move_handler(ship,event.key,False)

def check_btn_click(stats,btn,mouseX,mmouseY):
    if btn.rect.collidepoint(mouseX,mmouseY):
        stats.game_active = True
        
        

def move_handler(ship,key,isDown:bool):    
    if key == pygame.K_DOWN:
        ship.move_down = isDown 
    elif key == pygame.K_UP:
        ship.move_up = isDown
    elif key == pygame.K_LEFT:
        ship.move_left = isDown
    elif key == pygame.K_RIGHT:
        ship.move_right = isDown

def shoot(setObj,ship,key,screen,bullets):
    if key==pygame.K_SPACE:      
        if len(bullets)<setObj.max_bullet_num:  
            b = Bullet(screen,ship)
            bullets.add(b)
        else:
            pass
            #print("最多同时发射{0}颗子弹".format(setObj.max_bullet_num))

        
#刷新屏蔽的函数
def update_screen(setObj,ship,screen):
    '''不断刷新执行的函数,刷新屏幕显示'''
    #screen.fill(setObj.bg_color) #填充屏幕颜色
    ship.blitme() #绘制飞船外形   
    ship.update()           
    #让最近刷新的屏幕可见,新添加的显示对象必须在这个函数执行之前
    pygame.display.flip() 

def update_bullets(bullets):
    #绘制子弹外形
    for bullet in bullets.sprites():
        if bullet.rect.bottom<=0:
            bullets.remove(bullet)
        else:
            bullet.draw_bullet() 
    bullets.update() #执行容器元素中的update方法 这里是执行子弹类的 update 更新子弹的位置


def create_aliens(setObj,screen,aliens):
    '''创建外形人'''
    rows,cols,count = setObj.alien_info
    if len(aliens)>=count:
        return
    stx = setObj.alienW
    sty = setObj.alienH    
    for i in range(count):        
        if i>=len(aliens):
            aln = Alien(screen,setObj.rootUrl,setObj)
        else:
            aln = aliens.sprites()[i]
        
        col = i%cols
        row = int(i/cols)        
        aln.x = float(stx + col * aln.rect.width * 2)
        aln.y = float(sty + row * aln.rect.height * 2)
        aln.rect.x = aln.x
        aln.rect.y = aln.y
        if i < round(count/2):
            aln.dir = -1
        aliens.add(aln)

def update_aliens(aliens,ship,bullets,stats,screen,setObj,scoreView):
    for aln in aliens:
        aln.blitme()
        if aln.is_out_edge():
            aliens.remove(aln)

    aliens.update() #自动执行继承与sprite子类的update方法    
    check_bullet_alien_collide(bullets,aliens,setObj,scoreView)
    check_alien_ship_collide(aliens,ship,stats,screen,bullets,setObj,scoreView)


def check_bullet_alien_collide(bullets,aliens,setObj,scoreView):
    '''检测子弹和外星人的碰撞'''
    #返回一个dict
    collides = groupcollide(bullets,aliens,True,True) #两个bool参数表示是否删除对应group内的元素
    if len(collides) > 0:
        scoreView.set_score(setObj.shoot_score_add)        
        if scoreView.score % 30 == 0:
            increase_alien_speed(setObj)
      
def increase_alien_speed(setObj):
    setObj.alien_speed_add += setObj.alien_speed_increase

def check_alien_ship_collide(aliens,ship,stats,screen,bullets,setObj,scoreView):
    """检测飞船和外星人的碰撞"""   
    collidSp =  spritecollideany(ship,aliens)
    if collidSp:        
        stats.ship_left -= 1
        aliens.remove(collidSp)
        ship.reset()
        if stats.is_game_over():
            scoreView.set_score(-scoreView.score)  
            aliens.empty()
            bullets.empty()
            stats.reset_stats()        
            stats.game_active = False    
            create_aliens(setObj,screen,aliens)            
        #sleep(0.5)

    

def color_to_rgb(color:str)->tuple:
    '''把网页颜色转换成rgb颜色 传入的参数必须包含 rrggbb 这样的格式'''

    color = color.replace("0x","")
    color = color.replace("#","")
    retList = [int(color[i:i+2],16) for i in range(0,5,2)]

    return tuple(retList)

